package ch.so.sogis.interlis;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import ch.so.sogis.database.H2Obj;
import ch.so.sogis.interlis.converter.DM93toDM01SO24Converter;

import com.vividsolutions.jump.feature.FeatureDataset;

public class DM93ToDM01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		H2Obj myH2 = new H2Obj();
		
		String iliFile = "d:/geoprojekte/interlis/dm93/AVS_AV93_SO.ili";
		File dir = new File("d:/geoprojekte/interlis/dm93");
				
		String[] fileList = dir.list(new FilenameFilter() {
			public boolean accept(File d, String name) {
				return name.toLowerCase().endsWith(".itf");
			}
		});

		for(String f : fileList) {
			System.out.println("*****************************************************************");
		    System.out.println("Konvertieren von: " + dir.toString() + dir.separator + f);
		    
		    
		    // Itf einlesen
		    IliReader reader = new IliReader(iliFile);
			reader.compileModel();
			LinkedHashMap fd_hash = reader.readItf(dir.toString() + dir.separator + f, true);
		    System.out.println("groesse: "+fd_hash.size());
				
			// Daten in Datenbank schreiben
		    Connection conn = myH2.connect();
			Iterator it = fd_hash.entrySet().iterator();
			while(it.hasNext()) {
				Map.Entry ientry = (Map.Entry)it.next();		
				String featureName = ientry.getKey().toString();
				FeatureDataset fd = (FeatureDataset) ientry.getValue();
				String tableName = (featureName.substring(featureName.indexOf(".")+1)).replace(".", "_");
				//System.out.println(tableName +": "+ fd.size());
				//System.out.println("tablename: "+ tableName + " " + gem_bfs);
				myH2.insertFeatures(fd, tableName);
			}			
						
			
			// Konvertieren der Daten
			DM93toDM01SO24Converter Converter = new DM93toDM01SO24Converter(conn);
			HashMap fd_conv = Converter.convert();
			myH2.close();
			
			// Schreiben des ITFs
			
			//System.out.println(f.substring(0, f.lastIndexOf(".")));
			IliWriter myWriter = new IliWriter("d:/geoprojekte/interlis/dm01avso24.ili");
			myWriter.compileModel();
			myWriter.writeItf("d:/geoprojekte/interlis/"+f.substring(0, f.lastIndexOf("."))+"_dm01.itf", fd_conv);
		}

		
		
		
		
	}

}
